var dataTable;
var BSTable = function(options, $this) {
    var btGrid = typeof $this != "undefined" ? $this: options.btGrid ? options.btGrid: $("#dataGrid");
    var searchForm = options.searchForm ? options.searchForm: $("#searchForm");
    options = $.extend({
            btnSearch: $("#btnSearch"),
            bLengthChange: false,
            sScrollY: "100%",
            processing: false,
            autoWidth: true,
            info: true,
            paging: true,
            pagingType: "full_numbers",
            searching: false,
            ordering: false,
            serverSide: true,
            stateSave: false,
            lengthChange: false,
            lengthMenu: [10, 15, 25, 50, 75, 100],
            language: {
                url: ctxStatic + "/DataTables-1.10.20/local/dataTables_cn.txt",
            },
            draw: 1,
            pageLength: 15,
            responsive: true,
            scrollX: false,
            columnDefs: [{
                "defaultContent": "",
                "targets": "_all"
            }],
            ajax: {
                url: searchForm.attr("action"),
                type: "POST",
                dataSrx: "",
                data: function(data) {
                    var map = {};
                    var param = searchForm.serialize();
                    var params = param.split("&");
                    for (var i = 0; i < params.length; i++) {
                        var p = params[i];
                        var nv = p.split("=");
                        map[nv[0]] = nv[1]
                    }
                    console.log(map);
                    return $.extend({},
                        data, map)
                },
                beforeSend: function() {
                    js.loading()
                },
                dataType: "json",
                dataFilter: function(json) {
                    json = JSON.parse(json);
                    var returnData = {};
                    if (options.treeEnable) {
                        var treeData = toTreeData(json, "0");
                        console.log(treeData);
                        returnData.draw = returnData.draw+1;
                        returnData.recordsTotal = 0;
                        returnData.recordsFiltered = 0;
                        returnData.data = treeData
                    } else {
                        returnData.draw = json.draw;
                        returnData.recordsTotal = json.count;
                        returnData.recordsFiltered = json.count;
                        returnData.data = json.list == undefined ? [] : json.list
                    }
                    console.log(returnData);
                    return JSON.stringify(returnData);
                },
                error: function(data) {
                    if (typeof options.ajaxError == "function") {
                        options.ajaxError(data)
                    }
                    $(".btn").attr("disabled", false);
                    if (data.responseText && data.responseText != "") {
                        js.showErrorMessage(("操作失败，" + data.responseText + "！"))
                    }
                    js.closeLoading()
                }
            },
            columns: options.columnModel,
            btnEventBind: function(elements) {
                elements.each(function() {
                    var clickBinded = $(this).attr("data-click-binded");
                    if (clickBinded == undefined) {
                        $(this).attr("data-click-binded", true);
                        $(this).click(function() {
                            var se = $(this);
                            var url = se.attr("href");
                            var title = se.data("title");
                            if (title == undefined) {
                                title = se.attr("title")
                            }
                            var confirm = se.data("confirm");
                            var prompt = se.data("prompt");
                            if (confirm != undefined) {
                                js.confirm(confirm, url,
                                    function(data) {
                                        js.showMessage(data.message);
                                        if (data.result == "true") {
                                            var confirmSuccess = se.data("confirmSuccess");
                                            if (confirmSuccess != undefined) {
                                                try {
                                                    eval(confirmSuccess)
                                                } catch(e) {
                                                    js.print("confirmSuccess error: " + e)
                                                }
                                            }else{
                                                refresh();
                                            }
                                        }
                                    },
                                    "json")
                            } else {
                                if (prompt != undefined) {
                                    js.prompt(prompt, url,
                                        function(data) {
                                            js.showMessage(data.message);
                                            if (data.result == "true") {
                                                refresh()
                                            }
                                        },
                                        "json")
                                } else {
                                    var type = se.data("type");
                                    if (type != undefined && type == "layer") {
                                        js.layer.open({
                                            type: 2,
                                            title: title,
                                            shade: false,
                                            shadeClose: false,
                                            maxmin: true,
                                            area: ["100%", "100%"],
                                            content: url,
                                            end: function() {
                                                refresh()
                                            }
                                        })
                                    } else {
                                        if (type != undefined && type == "diagram") {
                                            js.layer.open({
                                                type: 2,
                                                title: title,
                                                shade: 0.3,
                                                shadeClose: true,
                                                maxmin: true,
                                                area: ["80%", "80%"],
                                                content: url,
                                                end: function() {}
                                            })
                                        } else {
                                            if (type != undefined && type == "form") {
                                                var formTitle = se.data("formtitle");
                                                var formUrl = se.data("formurl");
                                                var wh = se.data("wh");
                                                js.form(formTitle, url, formUrl,
                                                    function(data) {
                                                        if (data.result == "true") {
                                                            js.showMessage(data.message);
                                                            refresh()
                                                        } else {
                                                            js.showErrorMessage(data.message)
                                                        }
                                                    },
                                                    "json", wh)
                                            } else {
                                                var win;
                                                if (window.tabpanel) {
                                                    win = window
                                                }
                                                if (parent.tabpanel) {
                                                    win = window.parent
                                                }
                                                if (parent.parent.tabpanel) {
                                                    win = window.parent.parent
                                                }
                                                if (top.tabpanel) {
                                                    win = top
                                                }
                                                win.addTabPage($(this), title, url, true, true)
                                            }
                                        }
                                    }
                                }
                            }
                            return false
                        })
                    }
                });
                return self
            },
            "drawCallback": function(row, data) {
                if (typeof options.ajaxSuccess == "function") {
                    options.ajaxSuccess(data)
                }
                if (data && data.message) {
                    js.showMessage(data.message)
                }
                if (typeof options.btnEventBind == "function"/* && !options.treeEnable*/) {
                    options.btnEventBind($(".btnList"));
                }
                $(".btn").attr("disabled", false);
                resizeDataGrid();
                js.closeLoading()
            },
        },
        options);
    if (typeof options.btnEventBind == "function") {
        options.btnEventBind($(".btnTool"));
        options.btnSearch.click(function() {
            var btnSearch = $(this);
            if (searchForm.hasClass("d-none")) {
                searchForm.removeClass("d-none");
                btnSearch.html(btnSearch.html().replace("查询", "隐藏"))
            } else {
                searchForm.addClass("d-none");
                btnSearch.html(btnSearch.html().replace("隐藏", "查询"))
            }
            resizeDataGrid()
        })
    }
    if (options.treeEnable) {
        options.info = false;
        options.paging = false;
        options.treeGrid = {
            "left": 15,
            "expandAll": false,
            "expandIcon": '<span><i class="fa fa-plus-square"></i></span>',
            "collapseIcon": '<span><i class="fa fa-minus-square"></i></span>'
        }
    }
    dataTable = btGrid.DataTable(options);
    searchForm.submit(function() {
        refresh();
        return false
    });
    function refresh() {
        //btGrid.DataTable().ajax.reload();
        btGrid.DataTable().draw(false);
    }
    $(window).resize(function() {
        resizeDataGrid()
    });
    function resizeDataGrid() {
        var setGridHeight = function() {
            var gridHeight = btGrid.height();
            var gridParent = btGrid.parent();
            if (gridParent.length != 0) {
                gridHeight = gridParent.height()
            }
            js.print("设置前：window:" + $(window).height() + " body:" + $("body").height() + " table:" + btGrid.height() + " table-parent:" + gridHeight);
            gridHeight = ($(window).height() - $("body").height() + gridHeight);
            if (gridHeight < 150) {
                gridHeight = 150
            }
            gridParent.height(gridHeight);
            js.print("设置后：window:" + $(window).height() + " body:" + $("body").height() + " table:" + btGrid.height() + " table-parent:" + gridHeight)
        };
        setGridHeight()
    }
    function toTreeData(data, pid) {
        var result = [],
            temp;
        for (var i = 0; i < data.length; i++) {
            if (data[i].parentId == pid) {
                var obj = data[i];
                temp = toTreeData(data, data[i].id);
                if (temp.length > 0) {
                    obj.children = temp
                }
                result.push(obj)
            }
        }
        return result
    }
};
$.fn.BTGrid = function(option) {
    var $set = this.each(function() {
        var $this = $(this);
        var data = $this.data("btGrid");
        var options = typeof option === "object" && option;
        if (!data) {
            data = new BSTable(options, $this);
            window[$this.attr("id")] = data;
            $this.data("btGrid", data)
        }
    });
    return $set
};
function refresh() {
    $("#btGrid").DataTable().draw();
}